package com.llyb.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.llyb.lease.common.constants.RedisConstant;
import com.llyb.lease.common.exception.LeaseException;
import com.llyb.lease.common.jwt.JwtUtils;
import com.llyb.lease.common.result.ResultCodeEnum;
import com.llyb.lease.model.entity.SystemUser;
import com.llyb.lease.model.enums.BaseStatus;
import com.llyb.lease.web.admin.service.LoginService;
import com.llyb.lease.web.admin.service.SystemUserService;
import com.llyb.lease.web.admin.vo.login.CaptchaVo;
import com.llyb.lease.web.admin.vo.login.LoginVo;
import com.llyb.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired
    private SystemUserService systemUserService;
    @Override
    public CaptchaVo customGetCaptcha() {
        // 生成验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        String imgBase64 = specCaptcha.toBase64();
        String code = specCaptcha.text();

        // uuid 和 验证码 存入redis
        String uuidKey  = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString().replaceAll("-", "");
        redisTemplate.opsForValue().set(uuidKey,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        CaptchaVo captchaVo = new CaptchaVo(imgBase64, uuidKey);
        return captchaVo;

    }

    @Override
    public String customLogin(LoginVo loginVo) {
        // 1. 验证码是否过期
        Object o = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (ObjectUtils.isEmpty(o)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        // 2,  验证码是否正确
        if (!o.toString().equalsIgnoreCase(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        // 3. 账号是否存贮器
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser one = systemUserService.getOne(lambdaQueryWrapper);

        if (ObjectUtils.isEmpty(one)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        // 4, 账号和密码校验
        if (ObjectUtils.isEmpty(loginVo.getPassword())) {
            throw new LeaseException(ResultCodeEnum.ILLEGAL_REQUEST);
        }
        String password = DigestUtils.md5Hex(loginVo.getPassword());
        if (!one.getPassword().equals(password)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        // 5. 账号状态
        if (one.getStatus().equals(BaseStatus.DISABLE)) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        // 6. 发token
        String token = JwtUtils.createToken(one.getId(), one.getUsername());
        return token;
    }

    @Override
    public SystemUserInfoVo customInfo(String token) {
        Claims claims = JwtUtils.parseToken(token);
        Integer userId = (Integer) claims.get("userId");
        SystemUser systemUser = systemUserService.getById(userId);

        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        systemUserInfoVo.setName(systemUser.getName());
        return systemUserInfoVo;
    }

}
